package com.starbaba.mall.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;

import com.base.common.database.DaoHelper;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.starbaba.base.dao.LoanManagerBaseDao;
import com.starbaba.base.service.CommUserService;
import com.starbaba.base.service.impl.CommUserServiceImpl;
import com.starbaba.loanAccountInput.model.CommUserModel;
import com.starbaba.mall.entity.FanliWithdrawalEntity;
import com.starbaba.mall.service.FanliOrderService;
import com.starbaba.mall.service.LoanMallUserTaobaoOrderService;
import com.starbaba.mall.service.ProductItemService;
import com.starbaba.redis.JedisUtils;
import com.tuanzi.server.loan_base.constant.LoanRedisKey;
import com.tuanzi.server.loan_base.constant.MallFanliRecordStatus;
import com.tuanzi.server.loan_base.constant.mall.MallItemType;
import com.tuanzi.server.loan_base.model.db.Loan_Mall_Fanli_Record;
import com.tuanzi.server.loan_base.model.db.Loan_Mall_Item;
import com.tuanzi.server.loan_base.model.db.Loan_Mall_User_Taobao_Order;
import com.tuanzi.server.loan_base.util.Arith;
import com.tuanzi.server.loan_base.util.DateUtils;
import com.tuanzi.server.loan_base.util.PhoneNumNideUtil;

public class FanliOrderServiceImpl extends LoanManagerBaseDao implements FanliOrderService{
	
	private LoanMallUserTaobaoOrderService taobaoOrderService;
	private ProductItemService productItemService;
	private CommUserService commUserService;
	
	
	public FanliOrderServiceImpl(){
		this.productItemService = new ProductItemServiceImpl();
		this.taobaoOrderService = new  LoanMallUserTaobaoOrderServiceImpl();
		this.commUserService = new CommUserServiceImpl();
	}


	@Override
	public List<Loan_Mall_Fanli_Record> getList(Map<String, Object> paramsMap,
			int pageNo, int pageSize) {
		
		List<Loan_Mall_Fanli_Record> list = new ArrayList<Loan_Mall_Fanli_Record>();
				
        String sql = generateGetListSql(paramsMap) + " ORDER BY import_time DESC LIMIT ?,?"; 				
        
        try {
			
        	list = getDao().list(sql, Loan_Mall_Fanli_Record.class, pageNo, pageSize);
        	if(list != null) {
        		for(Loan_Mall_Fanli_Record record : list) {
        			record.setMobnum(PhoneNumNideUtil.hideNum(record.getMobnum()));
        		}
        	}
        	
		} catch (AppException e) {
			LogService.error(e);
		}
		
		
		return list;
	}

	@Override
	public int countList(Map<String, Object> paramsMap) {
		
		int result = 0;
		
		String sql = "SELECT COUNT(*) FROM (" + generateGetListSql(paramsMap) + ") AS a";
		
		try {
			
			result = getDao().getInt(sql);
			
		} catch (AppException e) {
			LogService.error(e);
		}
		return result;
	}

	
	@Override
	public int importTaokeOrderList(String[][] result) throws AppException {
		
		int rows = 1; //Excel表格的第几行
		int successNum = 0; //成功导入数据
		
		//导入时间
		Date import_time = new Date();
		
		for(String[] record: result){
			
			if (rows == 1) {
				rows++;
				continue;
			}
			
			String createtime = record[0];
			String tk_title = record[2];
			String source_id = record[3];
			int tk_number = (int)Float.parseFloat(record[6]);
			String tk_price = record[7];
			String statusInfo = record[8];
			String source = record[9];
			String pay_amount = record[12];
			String forecast_income = record[13];
			String updatetime = record[16];
			String commission = record[18];
			String busiid = record[24];  
			String category = record[25];
			
			//防止从excel读取到的订单号是浮点数
			if(busiid.contains(".")){
				busiid = busiid.substring(0, busiid.indexOf("."));
			}
			
			//检测淘宝妈妈导出的订单跟本地的订单是否匹配
			Loan_Mall_User_Taobao_Order taobaoOrder = taobaoOrderService.getLoanMallUserTaobaoOrder(busiid);
			if(taobaoOrder == null){
				continue;
			}
			
			Long userId = taobaoOrder.getUserid();
			
			//查询用户手机号
			String mobnum = getMobnum(userId);
			
			//转化订单状态为对应的返利状态
			int status = transformAlimamaOrderStatusToFanliStatus(statusInfo);
			
			//如果返利商品在本地商品库存在，取本地商品库的信息计算返利金额，否则取excel表格的效果预估字段作为返利金额
			Loan_Mall_Item item = productItemService.getLoanMallItemBySourceId(source_id);
			Float fanliAmount = 0.0f;
			String tk_img = null;
			if(item != null){
				
				tk_img = item.getImg();
				fanliAmount = calculateFanliAmount(item, tk_number);
				
			}else{
				
				tk_img = "https://img.tuanzidai.cn/loan/fanli_record_icon.png"; //用默认图标
				fanliAmount = Float.valueOf(forecast_income);
				
			}
			
			Loan_Mall_Fanli_Record fanliRecord = new Loan_Mall_Fanli_Record();
			fanliRecord.setBusiid(busiid);
			fanliRecord.setUserid(userId);
			fanliRecord.setMobnum(mobnum);
			fanliRecord.setValue(fanliAmount);
			fanliRecord.setCreatetime(DateUtils.formatYyyyMMddHHmmssToDate(createtime));
			fanliRecord.setUpdatetime(DateUtils.formatYyyyMMddHHmmssToDate(updatetime));
			fanliRecord.setSource_id(source_id);
			fanliRecord.setTk_title(tk_title);
			fanliRecord.setTk_price(Float.parseFloat(tk_price));
			fanliRecord.setPay_amount(Float.parseFloat(pay_amount));
			fanliRecord.setTk_img(tk_img);
			fanliRecord.setStatus(status);
			fanliRecord.setSource(source);
			fanliRecord.setCommission(Float.parseFloat(commission));
			fanliRecord.setTk_number(tk_number);
			fanliRecord.setCategory(category);
			fanliRecord.setImport_time(import_time);
			
			try {
				
				DaoHelper.startTransaction();
				
				//同一导入批次，允许导入相同的数据
				Loan_Mall_Fanli_Record oldRecord = getLoanMallFanliRecord(source_id, busiid, tk_number, DateUtils.formatDateToYyyyMMddHHmmss(import_time));
				if(oldRecord == null){
					
					Long id = getDao().addReturnGeneratedKey(fanliRecord);
					if(id > 0){
						
						successNum++;
						taobaoOrderService.updateLoanMallUserTaobaoOrder(busiid);  //更新为已导入、核对成功
						
					}
				}else{ //不同导入批次，对于同一条订单，更新订单状态、结算时间
					
					int num = updateLoanMallFanliRecord(oldRecord, updatetime, status, import_time);
					if(num > 0){
						
						successNum++;
						 
					}
					
				}
				
				DaoHelper.commitTransaction();
				
				JedisUtils.del(LoanRedisKey.MALL_ORDER_DETAIL + userId);
				
			} catch (AppException e) {
				LogService.error(e);
				DaoHelper.rollbackTransaction();
				return 0;
			}
			
		}
		
		//标记未导入的订单为核对失败（错误订单）
		taobaoOrderService.updateLoanMallUserTaoBaoOrder();
		
		return successNum;
	}
	
	
	@Override
	public int importRuyitouOrderList(String[][] result) throws AppException {
		
		int rows = 1; //Excel表格的第几行
		int successNum = 0; //成功导入数据
		
		//导入时间
		Date importTime = new Date();
		
		for(String[] record: result){
			
			if (rows == 1) {
				rows++;
				continue;
			}
			
			String createtime = record[0];               //创建时间
			String busiId = record[2];                   //订单id
			String statusInfo = record[3];               //订单状态
			String effectPredictionAmount = record[4];   //效果预估
			String updatetime = record[5];               //结算时间
			
			//防止从excel读取到的订单号是浮点数
			if(busiId.contains(".")){
				busiId = busiId.substring(0, busiId.indexOf("."));
			}
			
			//检测淘宝妈妈导出的订单跟本地的订单是否匹配
			Loan_Mall_User_Taobao_Order taobaoOrder = taobaoOrderService.getLoanMallUserTaobaoOrder(busiId);
			if(taobaoOrder == null){
				continue;
			}
			
			Long userId = taobaoOrder.getUserid();
			
			//查询用户手机号
			String mobnum = getMobnum(userId);
			
			//转化订单状态为对应的返利状态
			int status = transformAlimamaOrderStatusToFanliStatus(statusInfo);
			
			Float fanliAmount = Float.valueOf(effectPredictionAmount);  
			String tk_img = "https://img.tuanzidai.cn/loan/fanli_record_icon.png"; //用默认图标
			
			Loan_Mall_Fanli_Record fanliRecord = new Loan_Mall_Fanli_Record();
			fanliRecord.setBusiid(busiId);
			fanliRecord.setUserid(userId);
			fanliRecord.setMobnum(mobnum);
			fanliRecord.setValue(fanliAmount);
			fanliRecord.setCreatetime(DateUtils.formatYyyyMMddHHmmssToDate(createtime));
			fanliRecord.setUpdatetime(DateUtils.formatYyyyMMddHHmmssToDate(updatetime));
			fanliRecord.setTk_img(tk_img);
			fanliRecord.setStatus(status);
			fanliRecord.setImport_time(importTime);
			
			try {
				
				DaoHelper.startTransaction();
				
				//同一导入批次，允许导入相同的数据
				Loan_Mall_Fanli_Record oldRecord = getLoanMallFanliRecord(busiId, DateUtils.formatDateToYyyyMMddHHmmss(importTime));
				if(oldRecord == null){
					
					Long id = getDao().addReturnGeneratedKey(fanliRecord);
					if(id > 0){
						
						successNum++;
						taobaoOrderService.updateLoanMallUserTaobaoOrder(busiId);  //更新为已导入、核对成功
						
					}
				}else{ //不同导入批次，对于同一条订单，更新订单状态、结算时间
					
					int num = updateLoanMallFanliRecord(oldRecord, updatetime, status, importTime);
					if(num > 0){
						
						successNum++;
						 
					}
					
				}
				
				DaoHelper.commitTransaction();
				
				JedisUtils.del(LoanRedisKey.MALL_ORDER_DETAIL + userId);
				
			} catch (AppException e) {
				LogService.error(e);
				DaoHelper.rollbackTransaction();
				return 0;
			}
			
		}
		
		//标记未导入的订单为核对失败（错误订单）
		taobaoOrderService.updateLoanMallUserTaoBaoOrder();
		
		return successNum;
	}
	
	
	@Override
	public String exportList(Map<String, Object> paramsMap) {
		
		String sql = generateGetListSql(paramsMap) + " ORDER BY import_time DESC ";
		
		List<Loan_Mall_Fanli_Record> list = new ArrayList<Loan_Mall_Fanli_Record>();
		
		try {
			
			list = getDao().list(sql, Loan_Mall_Fanli_Record.class);
			
		} catch (AppException e) {
			LogService.error(e);
		}
		
		StringBuilder sb = new StringBuilder("下单时间,淘宝订单号,手机号,商品名称,商品id,订单金额,佣金金额	,返利金额,订单状态\r\n");
		
		for(Loan_Mall_Fanli_Record record: list){
			
			
			sb.append(record.getCreatetime() + ",")
			  .append(record.getBusiid() + ",")
			  .append(PhoneNumNideUtil.hideNum(record.getMobnum()) + ",")
			  .append(record.getTk_title() + ",")
			  .append(record.getSource_id() + ",")
			  .append(record.getPay_amount() + ",")
			  .append(record.getCommission() + ",")
			  .append(record.getValue() + ",")
			  .append(getFanliStatusNameByStatus(record.getStatus()) + "\r\n");
			
		}
		
		return sb.toString();
		
	}
	
	/**
	 * 获取返利状态对应的名称
	 * @param status
	 * @return
	 */
	private String getFanliStatusNameByStatus(Integer status){
		
		String name = "";
		switch (status) {
			case 100:
				name = "待确认收货";
				break;
				
			case 101:
				name = "即将返现";
				break;
				
			case 103:
				name = "已退款/已取消";
				break;
				
			case 201:
				name = "已返现";
				break;
	
			default:
				break;
		}
		
		return name;
		
	}
	
	
	/**
	 * 查询用户手机号
	 * @param userId
	 * @return
	 */
	private String getMobnum(Long userId){
		
		CommUserModel userModel =  commUserService.getCommUserById(userId);
		String mobnum = null;
		if(userModel != null){
			mobnum = userModel.getMobnum();
		}
		return mobnum;
	}
	
	/**
	 * 转化阿里妈妈订单状态为对应的返利状态
	 * @param statusInfo
	 * @return 订单状态
	 */
	private int transformAlimamaOrderStatusToFanliStatus(String statusInfo){
		
		int status = 0;
		if(statusInfo.equals("订单付款")){
			
			status = MallFanliRecordStatus.TO_BE_CONFIRMED;
			
		}else if(statusInfo.equals("订单结算")){
			
			status = MallFanliRecordStatus.TO_BE_PRESENT; 
			
			
		}else if(statusInfo.equals("订单失效")){
			
			status = MallFanliRecordStatus.CANCEL;
			
		}
		
		return status;
		
	}
	
	/**
	 * 计算返利金额：如果运营为商品配置了返利金额，且返利金额大于0，该金额作为订单的返利金额；否则动态计算返利金额
	 * @param item 商品信息
	 * @param tk_number 商品数量 
	 * @return
	 */
	private float calculateFanliAmount(Loan_Mall_Item item, int tk_number){
		
		Float fanliAmount = 0.0f;
		
		if(item.getFanli_amout() != null && item.getFanli_amout() > 0){
			
			fanliAmount = item.getFanli_amout() * tk_number;;
			
		}else if(StringUtils.isNotEmpty(item.getTk_rate())){
			
			float tkRate = Float.parseFloat(item.getTk_rate());
			float finalPrice =  item.getFinal_price();
			int isCouponItem = item.getIs_coupon_item();
			if(isCouponItem == MallItemType.COUPON_PRODUCT){  //优惠券商品，返利金额=(商品价格-代金券面额)*返利比例
				
				String couponInfo = item.getCoupon_info();  //优惠券面额
				Date couponStartTime = item.getCoupon_start_time();
				Date couponEndTime = item.getCoupon_end_time();
				Date time = new Date();
				if(StringUtils.isNotEmpty(couponInfo) && couponStartTime.getTime() <= time.getTime() && couponEndTime.getTime() >= time.getTime()){
					float couponPrice = Float.parseFloat(couponInfo);
					fanliAmount = (finalPrice * tk_number - couponPrice) * tkRate / 100;
				}
				
				
			}else{  //非优惠券商品，返利金额=商品价格*返利比例
				
				fanliAmount = finalPrice * tk_number * tkRate / 100 ;
			}
			
			
		}
		
		return fanliAmount;
	}
	
	private String generateGetListSql(Map<String, Object> paramsMap){
		
		StringBuilder sql = new StringBuilder("SELECT * FROM `loan_mall_fanli_record` WHERE 1=1 AND `status` !=  " + MallFanliRecordStatus.WITHDRAW);
		
		String startDate = (String) paramsMap.get("startDate");
		String endDate = (String) paramsMap.get("endDate");
		String source = (String) paramsMap.get("source");
		String category = (String) paramsMap.get("category");
		String status = (String) paramsMap.get("status");
		String busiid = (String) paramsMap.get("busiid");
		String source_id = (String) paramsMap.get("source_id");
		String tk_title = (String) paramsMap.get("tk_title");
		String mobnum = (String) paramsMap.get("mobnum");
		String userid = (String) paramsMap.get("userid");
		
		if(StringUtils.isNotEmpty(startDate)){
			sql.append(" AND createtime >= '" + DateUtils.getDateStartTime(startDate) + "'");
		}
		
		if(StringUtils.isNotEmpty(endDate)){
			sql.append(" AND createtime <= '" + DateUtils.getDateEndTime(endDate) + "'");
		}
		
		if(StringUtils.isNotEmpty(source)){
			sql.append(" AND source = '" + source + "'");
		}
		
		if(StringUtils.isNotEmpty(category)){
			sql.append(" AND category = '" + category + "'");
		}
		
		if(StringUtils.isNotEmpty(status)){
			sql.append(" AND status = '" + status + "'");
		}
		
		if(StringUtils.isNotEmpty(busiid)){
			sql.append(" AND busiid = '" + busiid + "'");
		}
		
		if(StringUtils.isNotEmpty(source_id)){
			sql.append(" AND source_id = '" + source_id + "'");
		}
		
		if(StringUtils.isNotEmpty(tk_title)){
			sql.append(" AND tk_title = '" + tk_title + "'");
		}
		
		if(StringUtils.isNotEmpty(mobnum)){
			sql.append(" AND mobnum = '" + mobnum + "'");
		}
		
		if(StringUtils.isNotEmpty(userid)){
			sql.append(" AND userid = '" + userid + "'");
		}
		
		return sql.toString();
		
	}
	
	/**
	 * 查询订单
	 * @param source_id 商品id
	 * @param busiid 订单id
	 * @param tk_number 订单数量
	 * @param status 订单状态
	 * @param import_time 导入时间
	 * @return
	 */
	private Loan_Mall_Fanli_Record getLoanMallFanliRecord(String source_id, String busiid, Integer tk_number, String import_time){
		
		Loan_Mall_Fanli_Record record = null;
		
		String sql = "SELECT * FROM `loan_mall_fanli_record` WHERE source_id = ? AND busiid = ? AND tk_number = ? AND import_time != ?";
		
		try {
			
			record = getDao().get(sql, Loan_Mall_Fanli_Record.class, source_id, busiid, tk_number, import_time);
			
		} catch (AppException e) {
			LogService.error(e);
		}
		
		return record;
		
	}
	
	/**
	 * 根据订单id查询订单
	 * @param busiId 订单id
	 * @return
	 */
	private Loan_Mall_Fanli_Record getLoanMallFanliRecord(String busiId, String importTime){
		
		Loan_Mall_Fanli_Record record = null;
		String sql = "SELECT * FROM `loan_mall_fanli_record` WHERE busiid = ? AND import_time != ?";
		
		try {
			
			record = getDao().get(sql, Loan_Mall_Fanli_Record.class, busiId, importTime);
			
		} catch (AppException e) {
			LogService.error(e);
		}
		
		return record;
		
	}
	
	/**
	 * 更新订单，订单状态变化规则：100——>101、103,  101——>103
	 * @param oldRecord 订单
	 * @param newStatus 新的订单状态
	 * @param updatetime 结算时间
	 * @param importtime 导入时间
	 * @return
	 */
	private int updateLoanMallFanliRecord(Loan_Mall_Fanli_Record oldRecord, String updatetime, int newStatus, Date importtime){
		
		int result = 0;
		int oldStatus = oldRecord.getStatus(); 
		if((oldStatus == MallFanliRecordStatus.TO_BE_CONFIRMED && (newStatus == MallFanliRecordStatus.TO_BE_PRESENT || newStatus == MallFanliRecordStatus.CANCEL)) 
				|| (oldStatus == MallFanliRecordStatus.TO_BE_PRESENT && newStatus == MallFanliRecordStatus.CANCEL)){
			
			oldRecord.setUpdatetime(DateUtils.formatYyyyMMddHHmmssToDate(updatetime));
			oldRecord.setStatus(newStatus);
			oldRecord.setImport_time(importtime);
			
			try {
				
				result = getDao().update(oldRecord, "id");
				
			} catch (AppException e) {
				LogService.error(e);
			}
			
		}
		
		return result;
		
	}


	@Override
	public List<FanliWithdrawalEntity> getWithdrawalList(
			Map<String, Object> paramsMap, int pageNo, int pageSize) {
		
		String sql = generateGetWithdrawalSql(paramsMap) + " ORDER BY createtime DESC LIMIT ?,?";
		List<FanliWithdrawalEntity> list = new ArrayList<FanliWithdrawalEntity>();
		try {
			
			list = getDao().list(sql, FanliWithdrawalEntity.class, pageNo, pageSize);
			
			String getCanRaisedBalanceSql = "SELECT SUM(value) value FROM loan_mall_fanli_record WHERE userid = ? AND STATUS = ? AND updatetime < ?";
			String getTotalWithdrawSql = "SELECT SUM(value) value FROM loan_mall_fanli_record WHERE userid = ? AND STATUS = ? AND createtime <= ?";
			int countDay = 7;
			//计算提现后的余额
			for(FanliWithdrawalEntity entity: list){
				
				Loan_Mall_Fanli_Record fanliRecord = getDao().get(getCanRaisedBalanceSql, Loan_Mall_Fanli_Record.class, entity.getUserid(), 
						MallFanliRecordStatus.TO_BE_PRESENT, DateUtils.formatDateToYyyyMMddHHmmss(new DateTime().plusDays(-countDay).toDate()));
				Float canBeRaisedBalance = 0.0f;
				if(fanliRecord != null && fanliRecord.getValue() != null){
					canBeRaisedBalance = fanliRecord.getValue();
				}
				
				Loan_Mall_Fanli_Record fanliRecord2 = getDao().get(getTotalWithdrawSql, Loan_Mall_Fanli_Record.class, entity.getUserid(), 
						MallFanliRecordStatus.WITHDRAW, entity.getCreatetime());
				
				Float withdrawBalance =  0.0f;
				if(fanliRecord2 != null && fanliRecord.getValue() != null){
					withdrawBalance = fanliRecord2.getValue();
				}
				
				Float balance =  Arith.add(canBeRaisedBalance, withdrawBalance);
				entity.setBalance(balance);
				
				entity.setMobnum(PhoneNumNideUtil.hideNum(entity.getMobnum()));
				
			}
			
		} catch (AppException e) {
			LogService.error(e);
		}
		
		return list;
	}


	@Override
	public int countWithdrawalList(Map<String, Object> paramsMap) {
		
		String sql = "SELECT COUNT(*) FROM (" + generateGetWithdrawalSql(paramsMap) + ") AS a";
		int result = 0;
		try {
			
			result = getDao().getInt(sql);
			
		} catch (AppException e) {
			LogService.error(e);
		}
		
		return result;
	}
	
	
	private String generateGetWithdrawalSql(Map<String, Object> paramsMap){
		
		StringBuilder sql = new StringBuilder("SELECT createtime, userid, mobnum, withdrawal_type, `value` FROM `loan_mall_fanli_record` WHERE STATUS = " + MallFanliRecordStatus.WITHDRAW);
		
		String startDate = (String) paramsMap.get("startDate");
		String endDate = (String) paramsMap.get("endDate");
		String withdrawalType = (String) paramsMap.get("withdrawalType");
		String mobnum = (String) paramsMap.get("mobnum");
		String userId = (String) paramsMap.get("userId");
		
		if(StringUtils.isNotEmpty(startDate)){
			sql.append(" AND createtime >= '" + DateUtils.getDateStartTime(startDate) + "'");
		}
		
		if(StringUtils.isNotEmpty(endDate)){
			sql.append(" AND createtime <= '" + DateUtils.getDateEndTime(endDate) + "'");
		}
		
		if(StringUtils.isNotEmpty(withdrawalType)){
			sql.append(" AND withdrawal_type = '" + withdrawalType + "'");
		}
		
		if(StringUtils.isNotEmpty(mobnum)){
			sql.append(" AND mobnum = '" + mobnum + "'");
		}
		
		
		if(StringUtils.isNotEmpty(userId)){
			sql.append(" AND userId = '" + userId + "'");
		}
		
		return sql.toString();
		
	}



}
